<?php


namespace app\admin\controller;


use app\admin\model\User;
use app\common\controller\admin\Base;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\SourceMaterialConfig;
use app\admin\model\Category;
use app\admin\model\RepaymentOrder;
use app\admin\model\WithdrawalOrder;

class Payview extends Base
{
    protected $noNeedLogin = [];

    protected $model;

    private static $tablesArr = [
        '1' => 'LoanOrder', //贷款
        '2' => 'RepaymentOrder', //还款
        '3' => 'WithdrawalOrder' //提现

    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\PayView();
    }

    public function index()
    {
        //设置过滤方法
        if ($this->request->isPost()) {
            $page = $this->request->post('page', 1);
            $size = $this->request->post('page_size', 10);
            $sort = $this->request->post('sort', 'id');
            $order = $this->request->post('order', 'desc');
            $adminId = $this->request->post('admin_id', '');
            $group = $this->request->post('group', '');
            $type = $this->request->post('type', '');
            $title = $this->request->post('title', '');
            $generate_type = $this->request->post('generate_type', '');
            $source = $this->request->post('source', '');
            $is_abandoned = $this->request->post('is_abandoned', '');
            $status = $this->request->post('status', '');
            $user_id = $this->request->post('user_id', '');
            $country_config_id = $this->request->post('country_config_id', '');
            if ($country_config_id != '') {
                $where['country_config_id'] = $country_config_id;
            }

            if ($adminId != '') {
                $where['admin_id'] = $adminId;
            }
            if ($group != '') {
                $where['group'] = $group;
            }
            if ($type != '') {
                $where['type'] = $type;
            }
            if ($generate_type != '') {
                $where['generate_type'] = $generate_type;
            }
            if ($source != '') {
                $where['source'] = $source;
            }
            if ($is_abandoned != '') {
                $where['is_abandoned'] = $is_abandoned;
            }
            if ($status != '') {
                $where['status'] = $status;
            }
            if ($user_id != '') {
                $where['user_id'] = $user_id;
            }
            if ($title != '') {
                $where['title'] = ['like', '%' . trim($title) . '%'];
            }
            $where['is_del'] = 0;
            $list = $this->model
                ->field('*')
                ->where($where)
                ->page($page, $size)
                ->order($sort, $order)
                ->select()
                ->toArray();
            $user = new User();
            $list = $user->formatOrderData($list);
            $types = array_column($list, 'type');
            //去重
            $types = array_flip($types);
            $types = array_keys($types);
            $catList = Category::where(['nickname' => ['in', $types]])->select()->toArray();
            $catList = array_column($catList, null, 'nickname');
            //取出所有国家列表
            $countryConfigList = \app\admin\model\CountryConfig::select()->toArray();
            $countryConfigList = array_column($countryConfigList, null, 'id');
            foreach ($list as $key => $value) {
                $value['type_name'] = empty($catList[$value['type']]) ? '' : $catList[$value['type']]['name'];
                $value['country_name'] = empty($countryConfigList[$value['country_config_id']]) ? '' : $countryConfigList[$value['country_config_id']]['name'];
                $value['diff_time'] = date('Y-m-d H:i:s', $value['diff_time']);
                $list[$key] = $value;
            }
            $total = $this->model->where($where)->count('id');
            $totalPage = ceil($total / $size);
            $data = [
                'total' => $total,
                'list' => $list,
                'totalPage' => $totalPage
            ];
            $this->success('列表', '', $data);
        }
    }

    /**
     * 重写新增方法
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = $name . '.add';
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->admin['id'];
                    //判断素材是否存在
                    if (empty($params['title']) || empty($params['content'])) {
                        $sourceMaterialInfo = SourceMaterialConfig::where(['secondary_classification' => $params['type']])->find();
                        if (empty($sourceMaterialInfo)) {
                            $this->error('素材不存在');
                        }
                        $params['title'] = empty($params['title']) ? $sourceMaterialInfo['title'] : $params['title'];
                        $params['content'] = empty($params['content']) ? $sourceMaterialInfo['content'] : $params['content'];
                    }
                    //根据dataId处理对应逻辑
                    $className = 'app\admin\model\\' . self::$tablesArr[$params['group']];
                    $object = new $className();
                    $orderInfo = $object->get($params['data_id']);
                    if (empty($orderInfo)) {
                        $this->error('对应订单不存在');
                    }
                    //判断贷款是否成功
                    if ($orderInfo['status'] == 3 && $params['group'] == 1) {
                        $this->error('贷款订单已完成,该订单不允许继续生成支付页面!');
                    }
                    $userInfo = User::get($params['user_id']);
                    $setData = [
                        'title' => $params['title'],
                        'content' => $params['content'],
                        'group' => $params['group'],
                        'type' => $params['type'],
                        'generate_type' => $params['generate_type'],
                        'user_id' => $params['user_id'],
                        'amount_money' => $params['amount_money'],
                        'is_quota' => $params['is_quota'],
                        'source' => $orderInfo['source'],
                        'app_base_id' => $orderInfo['app_base_id'],
                        'data_id' => $params['data_id'],
                        'partner_id' => $orderInfo['partner_id'],
                        'customer_service_group_id' => $orderInfo['customer_service_group_id'],
                        'customer_service_personnel_id' => $orderInfo['customer_service_personnel_id'],
                        'pay_config_id' => empty($params['pay_config_id']) ? '' : $params['pay_config_id'],
                        'country_config_id' => $userInfo['country_config_id']
                    ];
                    $result = $this->model->allowField(true)->save($setData);
                    //生成支付页面后  用户信息修改
                    User::update(['is_check_kf_switch' => 1], ['id' => $params['user_id']]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('添加成功');
                } else {
                    $this->error('添加失败');
                }
            }
            $this->error('参数不能为空！');
        }
    }

    /**
     * 数据的设置操作, 目前有  开关  是否默认  状态
     */
    public function setup($ids = "")
    {
        $type = $this->request->post("type");
        $val = $this->request->post("val");
        $field = $type;
        switch ($type) {
            case 'switch':
            case 'status':
            case 'is_abandoned':
                $data[$field] = $val;
                $where['id'] = ['in', $ids];
                break;
            case 'is_default':
                if ($val == 1) {
                    $oldwhere['id'] = ['neq', $ids];
                    $oldwhere['is_default'] = 1;
                    $this->model->update(['is_default' => 0], $oldwhere);
                    $data[$field] = $val;
                    $where['id'] = $ids;
                }
                break;
            default:
                $this->error('不存在的业务');
                break;
        }
        $this->model->update($data, $where);
        $this->success('操作成功');
    }
}